﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ParsecParser;
using ParsecClient.Classes;

namespace ParsecClient
{
    /// <summary>
    /// Interaction logic for StatsOverview.xaml
    /// </summary>
    public partial class StatStopWatch : Window
    {
        public DateTime? StopWatchStartTime = null;
        public CombatLog LocalLog = null;
        public StatStopWatch()
        {
            InitializeComponent();
            LocalLog = new CombatLog();
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, new ExecutedRoutedEventHandler(delegate(object sender, ExecutedRoutedEventArgs args) { this.Close(); })));
        }
        public void SetStats(List<CombatLogEvent> events)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { SetStats(events); });
                return;
            }
            else
            {
                Topmost = true;
                if (events != null && events.Count > 0)
                {
                    if (StopWatchStartTime.HasValue)
                    {
                        if (events.Count > 0)
                        {
                            foreach (var e in events)
                            {
                                LocalLog.AddEvent(e);
                            }
                            if (LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds > 0)
                            {
                                lblLengthValue.Text = String.Format("{0:hh\\:mm\\:ss\\.fff}", LocalLog.LogStatistics.CombatTimeSpan);
                                lblDamageOutValue.Text = LocalLog.LogStatistics.DamageOut.ToString("N0");
                                lblDamageOutValue2.Text = (LocalLog.LogStatistics.DamageOut / LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds).ToString("N0");
                                lblHealsOutValue.Text = LocalLog.LogStatistics.HealOut.ToString("N0");
                                lblHealsOutValue2.Text = (LocalLog.LogStatistics.HealOut / LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds).ToString("N0");
                                lblHealsOutValue3.Text = (LocalLog.LogStatistics.HealOut > 0 ? ((double)LocalLog.LogStatistics.EffectiveHealOut / (double)LocalLog.LogStatistics.HealOut) : 0).ToString("P1");
                                lblHealsOutValue4.Text = (LocalLog.LogStatistics.EffectiveHealOut / LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds).ToString("N0");
                                lblDamageInValue.Text = LocalLog.LogStatistics.DamageIn.ToString("N0");
                                lblDamageInValue2.Text = (LocalLog.LogStatistics.DamageIn / LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds).ToString("N0");
                                lblHealsInValue.Text = LocalLog.LogStatistics.HealIn.ToString("N0");
                                lblHealsInValue2.Text = (LocalLog.LogStatistics.HealIn / LocalLog.LogStatistics.CombatTimeSpan.TotalSeconds).ToString("N0");
                            }
                            else
                                ClearStats();
                        }
                        else
                            ClearStats();
                    }
                }
                else
                    ClearStats();
            }
        }
        public void ClearStats()
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { ClearStats(); });
                return;
            }
            else
            {
                lblLengthValue.Text = "";
                lblDamageOutValue.Text = "";
                lblHealsOutValue.Text = "";
                lblDamageInValue.Text = "";
                lblHealsInValue.Text = "";
                lblDamageOutValue2.Text = "";
                lblHealsOutValue2.Text = "";
                lblDamageInValue2.Text = "";
                lblHealsInValue2.Text = "";
                lblHealsOutValue3.Text = "";
                lblHealsOutValue4.Text = "";
            }
        }
        public void StopIfWatching()
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { StopIfWatching(); });
                return;
            }
            else
            {
                StopWatchStartTime = null;
                btnToggle.Content = "Start";
            }
        }
        public double GetBackgroundOpacity()
        {
            return BorderBackground.Opacity;
        }
        public void SetBackgroundOpacity(double opacity)
        {

            BorderBackground.Opacity = opacity;
            BorderSolid.Opacity = opacity;
            BorderBlur.Opacity = opacity;
        }

        public void DragWindow(object sender, MouseButtonEventArgs args)
        {
            try
            {
                this.WindowState = WindowState.Normal;
                DragMove();
                args.Handled = true;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out DragWindow", this.Title), ex, null, true);
            }
        }
        private void btnIncreaseOpacity_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (BorderBackground.Opacity < 1)
                {
                    BorderBackground.Opacity += .1;
                    BorderSolid.Opacity += .1;
                    BorderBlur.Opacity += .1;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnIncreaseOpacity_Click", this.Title), ex, null, true);
            }
        }

        private void btnDecreaseOpacity_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (BorderBackground.Opacity > 0)
                {
                    BorderBackground.Opacity -= .1;
                    BorderSolid.Opacity -= .1;
                    BorderBlur.Opacity -= .1;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnDecreaseOpacity_Click", this.Title), ex, null, true);
            }
        }

        private void btnIncreaseSize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.Width < 1000)
                {
                    this.Width += 10;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnIncreaseSize_Click", this.Title), ex, null, true);
            }
        }

        private void btnDecreaseSize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.Width > 100)
                {
                    this.Width -= 10;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnIncreaseSize_Click", this.Title), ex, null, true);
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Application.Current.MainWindow != null)
                {
                    ((ParsecWindow)Application.Current.MainWindow).btnStatStopWatch.IsChecked = false;
                }
                this.Hide();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnIncreaseSize_Click", this.Title), ex, null, true);
            }
        }

        private void btnToggle_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //set start time
                if (Application.Current.MainWindow != null)
                {
                    if (StopWatchStartTime.HasValue)
                    {
                        StopWatchStartTime = null;
                        btnToggle.Content = "Start";
                    }
                    else
                    {
                        LocalLog = new CombatLog();
                        CombatLog mainWindowLog = ((ParsecWindow)Application.Current.MainWindow).Log;
                        if (mainWindowLog != null)
                        {
                            //if in combat include current fight
                            StopWatchStartTime = mainWindowLog.CurrentLogDate;
                            //SetStats(MainUIWindow.Log.Fights.Values.ToList());
                            List<CombatDetails> existingFights = mainWindowLog.GetFightList();
                            if (existingFights != null && existingFights.Count > 0)
                            {
                                //get current log state and set it up.
                                if (!LocalLog.IsInCombat && mainWindowLog.IsInCombat)
                                {
                                    LocalLog.LastFightIndex++;
                                    LocalLog.AddOrUpdateFight(LocalLog.LastFightIndex, new CombatDetails() { StartCombat = mainWindowLog.CurrentLogDate, CharacterName = mainWindowLog.CharacterName, LogStateAtStart = new LogState() { CharacterName = mainWindowLog.CharacterName, GuardCount = mainWindowLog.CurrentLogState.GuardCount } });
                                }
                                LocalLog.IsInCombat = mainWindowLog.IsInCombat;
                                LocalLog.FloatingEndCombatTime = mainWindowLog.FloatingEndCombatTime;
                                LocalLog.IgnoreCombatWindowStart = mainWindowLog.IgnoreCombatWindowStart;
                                LocalLog.IgnoreCombatWindowEnd = mainWindowLog.IgnoreCombatWindowEnd;
                                LocalLog.ReviveWindowStart = mainWindowLog.ReviveWindowStart;
                                LocalLog.ReviveWindowEnd = mainWindowLog.ReviveWindowEnd;
                                List<CombatLogEvent> events = new List<CombatLogEvent>();
                                foreach (var f in existingFights)
                                {
                                    events.AddRange(f.GetEvents().Where(x => x.TimeStamp.CompareTo(StopWatchStartTime.Value) >= 0).ToList());
                                }
                                SetStats(events);
                            }
                            else
                                ClearStats();
                        }
                        else
                            StopWatchStartTime = DateTime.Today;
                        btnToggle.Content = "Stop";
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", string.Format("Error on {0} Pop Out btnToggle_Click", this.Title), ex, null, true);
            }
        }
    }
}

